package main

import "fmt"

func testMake1() {
  a := make([]int,1/*切片长度；有权操作的位数*/,10/*切片容量；该切片最长为10*/)

  a[0] = 10

  //a[1] = 20 //panic: runtime error: index out of range [1] with length 1
  a = append(a, 11)

  fmt.Printf("a=%v\n",a)
}

func testMake2() {
  a := make([]int,1,10)

  a[0] = 10
  fmt.Printf("a=%v addr:%p len:%d cap:%d\n",a,a,len(a),cap(a))

  a = append(a, 11)
  fmt.Printf("a=%v addr:%p len:%d cap:%d\n",a,a,len(a),cap(a))

  for i := 0; i < 8; i++ {
    a = append(a,i)
    fmt.Printf("a=%v addr:%p len:%d cap:%d\n",a,a,len(a),cap(a))
  }

  //此时再append的话,切片就需要进行扩容了(会改变切片此时的内存地址,容量大小x2)
  a = append(a,1000)
  fmt.Printf("a=%v addr:%p len:%d cap:%d\n",a,a,len(a),cap(a))

/*
   a=[10] addr:0xc0000121e0 len:1 cap:10
   a=[10 11] addr:0xc0000121e0 len:2 cap:10
   a=[10 11 0] addr:0xc0000121e0 len:3 cap:10
   a=[10 11 0 1] addr:0xc0000121e0 len:4 cap:10
   a=[10 11 0 1 2] addr:0xc0000121e0 len:5 cap:10
   a=[10 11 0 1 2 3] addr:0xc0000121e0 len:6 cap:10
   a=[10 11 0 1 2 3 4] addr:0xc0000121e0 len:7 cap:10
   a=[10 11 0 1 2 3 4 5] addr:0xc0000121e0 len:8 cap:10
   a=[10 11 0 1 2 3 4 5 6] addr:0xc0000121e0 len:9 cap:10
   a=[10 11 0 1 2 3 4 5 6 7] addr:0xc0000121e0 len:10 cap:10
   a=[10 11 0 1 2 3 4 5 6 7 1000] addr:0xc00007e000 len:11 cap:20   ←←← 此处进行了扩容,地址改变了,cap(容量)翻倍了
*/
}

func testMake3(){
  var a []int
  a = make([]int,5,10)
  a = append(a,10)
  fmt.Printf("a=%v\n",a) //a=[0 0 0 0 0 10]

  //todo 想要append的是第一个元素怎么办？

  //========================================
  b := make([]int,0,10)
  fmt.Printf("b=%v len:%d cap:%d \n",b,len(b),cap(b))
  b = append(b,100)
  fmt.Printf("b=%v len:%d cap:%d \n",b,len(b),cap(b))
/*
   b=[] len:0 cap:10
   b=[100] len:1 cap:10
*/
}

func testCap(){
  a := [...]string {"a","b","c","d","e","f","g","h"}
  b := a[1:3]
  fmt.Printf("b:%v len:%d cap:%d\n",b,len(b),cap(b)) //b:[b c] len:2 cap:7
}

func testCap2(){
  a := [...]string {"a","b","c","d","e","f","g","h"}
  b := a[1:3]
  fmt.Printf("b:%v len:%d cap:%d\n",b,len(b),cap(b)) //b:[b c] len:2 cap:7

  b = b[:cap(b)] //切片还可以被切片
  fmt.Printf("after reslice :b:%v len:%d cap:%d\n",b,len(b),cap(b))
}

func main() {
  //testMake1()

  //testMake2()

  //testMake3()

  //testCap()

  testCap2()
}
